package com.xunyin.modules.version2.mtstore.rest;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.xunyin.api.ApiResult;
import com.xunyin.api.XunyinException;
import com.xunyin.modules.log.AppLog;
import com.xunyin.modules.mtorder.service.mapper.MtOrderMapper;
import com.xunyin.modules.mtservicefac.domain.MtServiceFac;
import com.xunyin.modules.mtservicefac.service.MtServiceFacService;
import com.xunyin.modules.mtservicefac.vo.MtServiceFacVo;
import com.xunyin.modules.mtstore.domain.MtStoreRoom;
import com.xunyin.modules.mtstore.service.MtStoreRoomService;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.modules.mtstore.service.dto.StoreDto;
import com.xunyin.modules.mtstore.service.mapper.MtStoreMapper;
import com.xunyin.modules.mtstore.service.mapper.MtStoreRoomMapper;
import com.xunyin.modules.mtstore.vo.MtStoreNameVo;
import com.xunyin.modules.mtstore.vo.MtStoreRoomVo;
import com.xunyin.modules.mtstore.vo.MtStoreVo;
import com.xunyin.modules.shareorder.bo.OrderDateHour;
import com.xunyin.modules.shareorder.param.TShareOrderParam;
import com.xunyin.modules.shareorder.service.TShareOrderService;
import com.xunyin.modules.shareorder.service.dto.OrderStatDto;
import com.xunyin.modules.shareorder.service.mapper.TShareOrderMapper;
import com.xunyin.utils.DateUtil;
import com.xunyin.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 门店控制器
 * </p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 *
 * @since 2023-4-11
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "门店模块", tags = "共享空间:门店模块")
public class ClientStoreController {

    private final MtStoreMapper mtStoreMapper;

    private final RedisUtils redisUtils;

    private final StoreService storeService;

    private final MtStoreRoomService mtStoreRoomService;

    private final MtStoreRoomMapper mtStoreRoomMapper;

    private final MtOrderMapper mtOrderMapper;

    private final TShareOrderMapper tShareOrderMapper;

    private final TShareOrderService tShareOrderService;

    /**
     * 服务设施服务接口
     */
    private final MtServiceFacService mtServiceFacService;



    /**
     * 首页-根据城市获取门店列表信息
     */
    @AppLog(value = "首页-根据城市获取门店列表信息", type = 1)
    //@AuthCheck
    @PostMapping("/store/storeList") // @Validated @RequestBody
    @ApiOperation(value = "首页-根据城市获取门店列表信息", notes = "首页-根据城市获取门店列表信息")
    public ApiResult<List<MtStoreVo>> getStoreInfo(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        String cityCode = param.get("cityCode") == null ? "" : param.get("cityCode").toString();
        String latitude = param.get("latitude") == null ? "" : param.get("latitude").toString();
        String longitude = param.get("longitude") == null ? "" : param.get("longitude").toString();

        //String cityCode = request.getParameter("cityCode");
        //String latitude = request.getParameter("latitude");
        //String longitude = request.getParameter("longitude");

        List<MtStoreVo> list = mtStoreMapper.getStoreList(cityCode, latitude, longitude);
        for (MtStoreVo mtStoreVo : list) {
            List<MtStoreRoomVo> storeRoomList = mtStoreVo.getStoreRoomList();
            if (storeRoomList != null && storeRoomList.size() > 0) {
                for (MtStoreRoomVo mtStoreRoomVo : storeRoomList) {
                    //DateUtil.parseDate2String(teaOrder.getTeaServerEndTime(), "yyyy-MM-dd HH:mm")
                    if (mtStoreRoomVo.getServerEndTime() != null) {
                        String endTimeStr = DateUtil.parseDate2String(mtStoreRoomVo.getServerEndTime(), "yyyy-MM-dd HH:mm");
                        endTimeStr = endTimeStr.substring(11);
                        mtStoreRoomVo.setServerEndTimeStr(endTimeStr);
                    }
                    String serviceFacIdStr = mtStoreRoomVo.getServiceFacIds();
                    if (serviceFacIdStr != null || !"".equals(serviceFacIdStr)) {
                        String[] serviceFacIds = serviceFacIdStr.split(",");
                        List<Map<String, String>> iconList = new ArrayList<Map<String, String>>();
                        for (String serviceFacId : serviceFacIds) {
                            Map<String, String> serviceFacMap = new HashMap<String, String>();
                            serviceFacMap.put("id", serviceFacId);
                            serviceFacMap.put("icon", redisUtils.getY("serviceFac_" + serviceFacId));
                            iconList.add(serviceFacMap);
                            //iconList.add(redisUtils.getY("serviceFac_"+serviceFacId));
                        }
                        mtStoreRoomVo.setIconList(iconList);
                    }
                }
            }
        }
        log.info("getStoreInfo -> list={}", list.toString());
        return ApiResult.ok(list);

    }

    /**
     * 首页-根据城市获取门店列表信息V2
     */
    @AppLog(value = "首页-根据城市获取门店列表信息V2", type = 1)
    //@AuthCheck
    @PostMapping("/store/storeListV2") // @Validated @RequestBody
    @ApiOperation(value = "首页-根据城市获取门店列表信息V2", notes = "首页-根据城市获取门店列表信息V2")
    public ApiResult<List<MtStoreVo>> getStoreInfoV2(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        //String cityCode = param.get("cityCode") == null ? "" : param.get("cityCode").toString();
        String latitude = param.get("latitude") == null ? "" : param.get("latitude").toString();
        String longitude = param.get("longitude") == null ? "" : param.get("longitude").toString();

        //String cityCode = request.getParameter("cityCode");
        //String latitude = request.getParameter("latitude");
        //String longitude = request.getParameter("longitude");

        List<MtStoreVo> list = mtStoreMapper.getStoreListV2(latitude, longitude);
        for (MtStoreVo mtStoreVo : list) {
            List<MtStoreRoomVo> storeRoomList = mtStoreVo.getStoreRoomList();
            if (storeRoomList != null && storeRoomList.size() > 0) {
                for (MtStoreRoomVo mtStoreRoomVo : storeRoomList) {
                    //DateUtil.parseDate2String(teaOrder.getTeaServerEndTime(), "yyyy-MM-dd HH:mm")
                    if (mtStoreRoomVo.getServerEndTime() != null) {
                        String endTimeStr = DateUtil.parseDate2String(mtStoreRoomVo.getServerEndTime(), "yyyy-MM-dd HH:mm");
                        endTimeStr = endTimeStr.substring(11);
                        mtStoreRoomVo.setServerEndTimeStr(endTimeStr);
                    }

                    String serviceFacIdStr = mtStoreRoomVo.getServiceFacIds();
                    if (serviceFacIdStr != null || !"".equals(serviceFacIdStr)) {
                        String[] serviceFacIds = serviceFacIdStr.split(",");
                        List<Map<String, String>> iconList = new ArrayList<Map<String, String>>();
                        for (String serviceFacId : serviceFacIds) {
                            Map<String, String> serviceFacMap = new HashMap<String, String>();
                            serviceFacMap.put("id", serviceFacId);
                            serviceFacMap.put("icon", redisUtils.getY("serviceFac_" + serviceFacId));
                            iconList.add(serviceFacMap);
                            //iconList.add(redisUtils.getY("serviceFac_"+serviceFacId));
                        }
                        mtStoreRoomVo.setIconList(iconList);
                    }

                    // 获取包间下已预定的小时数
                    TShareOrderParam tShareOrderParam = new TShareOrderParam();
                    tShareOrderParam.setTeaChildId(mtStoreRoomVo.getRoomId());
                    List<OrderDateHour> hourList = tShareOrderService.getTimeListOrderV2(tShareOrderParam);
                    mtStoreRoomVo.setHourList(hourList);

                }
            }
        }
        log.info("getStoreInfo -> list={}", list.toString());
        return ApiResult.ok(list);

    }

    /**
     * 获取门店的总营收(元)、预约订单金额(元)、购买卡券金额(元)、充值金额(元)
     */
    @AppLog(value = "获取门店的总营收(元)、预约订单金额(元)、购买卡券金额(元)、充值金额(元)", type = 1)
    //@AuthCheck
    @PostMapping("/store/getStoreStat")
    @ApiOperation(value = "获取门店的总营收(元)、预约订单金额(元)、购买卡券金额(元)、充值金额(元)", notes = "获取门店的总营收(元)、预约订单金额(元)、购买卡券金额(元)、充值金额(元)")
    public ApiResult<Map<String, Object>> getStoreStat(HttpServletRequest request, @Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Double rechargeOrderMoney = mtOrderMapper.sumRechargeOrderMoney(tShareOrderParam.getStoreId());
        Double couponOrderMoney = mtOrderMapper.sumCouponOrderMoney(tShareOrderParam.getStoreId());
        Double realOrderMoney = tShareOrderMapper.sumRealOrderMoney(tShareOrderParam.getStoreId());
        Double yuyueOrderMoney = tShareOrderMapper.sumOrderMoney(tShareOrderParam.getStoreId());

        // 获取总营收
        // 进行加法运算
        BigDecimal b1 = new BigDecimal(rechargeOrderMoney);
        BigDecimal b2 = new BigDecimal(couponOrderMoney);
        Double totalMoney = b1.add(b2).doubleValue();
        BigDecimal b3 = new BigDecimal(totalMoney);
        BigDecimal b4 = new BigDecimal(yuyueOrderMoney);
        totalMoney = b3.add(b4).doubleValue();

        Map<String, Object> reData = new HashMap<>();
        reData.put("rechargeOrderMoney", rechargeOrderMoney);
        reData.put("couponOrderMoney", couponOrderMoney);
        reData.put("yuyueOrderMoney", yuyueOrderMoney);
        reData.put("realOrderMoney", realOrderMoney);
        reData.put("totalMoney", totalMoney);
        return ApiResult.ok(reData);
    }

    /**
     * 根据天数获取订单（已支付、服务中、已完成）的实际支付金额总数、订单总数
     */
    @AppLog(value = "根据天数获取订单（已支付、服务中、已完成）的实际支付金额总数、订单总数", type = 1)
    //@AuthCheck
    @PostMapping("/store/getOrderStatByDayNum")
    @ApiOperation(value = "根据天数获取订单（已支付、服务中、已完成）的实际支付金额总数、订单总数", notes = "根据天数获取订单（已支付、服务中、已完成）的实际支付金额总数、订单总数")
    public ApiResult<Map<String, Object>> getOrderStatByDayNum(HttpServletRequest request, @Validated @RequestBody TShareOrderParam tShareOrderParam) {
        OrderStatDto orderStatDto = tShareOrderService.getOrderStatByDayNum(tShareOrderParam.getStoreId(),tShareOrderParam.getDayNum());
        Map<String, Object> reData = new HashMap<>();
        reData.put("orderStatDto", orderStatDto);
        return ApiResult.ok(reData);
    }


    /**
     * 获取门店名称列表
     */
    @AppLog(value = "获取门店名称列表", type = 1)
    //@AuthCheck
    @PostMapping("/store/storeNameList")
    @ApiOperation(value = "获取门店名称列表", notes = "获取门店名称列表")
    public ApiResult<List<MtStoreNameVo>> getStoreNameList(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        Integer isAddPlatFlag = (param.get("isAddPlatFlag") == null) ? 0 : Integer.parseInt(param.get("isAddPlatFlag").toString());
        List<MtStoreNameVo> list = mtStoreMapper.getStoreNameList();
        List<MtStoreNameVo> reList = new ArrayList<MtStoreNameVo>();
        if (isAddPlatFlag > 0) {
//            MtStoreNameVo mtStoreNamePlatVo = new MtStoreNameVo();
//            mtStoreNamePlatVo.setStoreId(0);
//            mtStoreNamePlatVo.setStoreName("平台通用");
//            reList.add(mtStoreNamePlatVo);
        }
        for (MtStoreNameVo mtStoreNameVo : list) {
            reList.add(mtStoreNameVo);
        }

        log.info("getStoreNameList -> reList={}", reList.toString());
        return ApiResult.ok(reList);
    }

    /**
     * 根据门店Id获取该门店的房间列表
     */
    @AppLog(value = "根据门店Id获取该门店的房间列表", type = 1)
    //@AuthCheck
    @PostMapping("/storeRoom/storeRoomList")
    @ApiOperation(value = "根据门店Id获取该门店的房间列表", notes = "根据门店Id获取该门店的房间列表")
    public ApiResult<List<MtStoreRoomVo>> getStoreRoomList(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        Integer storeId = (param.get("storeId") == null) ? 0 : Integer.parseInt(param.get("storeId").toString());
        List<MtStoreRoomVo> storeRoomList = mtStoreRoomMapper.getStoreRoomListForAdmin(storeId);
        if (storeRoomList != null && storeRoomList.size() > 0) {
            for (MtStoreRoomVo mtStoreRoomVo : storeRoomList) {
                if (mtStoreRoomVo.getServerEndTime() != null) {
                    String endTimeStr = DateUtil.parseDate2String(mtStoreRoomVo.getServerEndTime(), "yyyy-MM-dd HH:mm");
                    endTimeStr = endTimeStr.substring(11);
                    mtStoreRoomVo.setServerEndTimeStr(endTimeStr);
                }
                String serviceFacIdStr = mtStoreRoomVo.getServiceFacIds();
                if (serviceFacIdStr != null || !"".equals(serviceFacIdStr)) {
                    String[] serviceFacIds = serviceFacIdStr.split(",");
                    List<Map<String, String>> iconList = new ArrayList<Map<String, String>>();
                    for (String serviceFacId : serviceFacIds) {
                        Map<String, String> serviceFacMap = new HashMap<String, String>();
                        serviceFacMap.put("id", serviceFacId);
                        serviceFacMap.put("icon", redisUtils.getY("serviceFac_" + serviceFacId));
                        iconList.add(serviceFacMap);
                        //iconList.add(redisUtils.getY("serviceFac_"+serviceFacId));
                    }
                    mtStoreRoomVo.setIconList(iconList);
                }
            }
        }
        log.info("getStoreRoomList -> storeRoomList={}", storeRoomList.toString());
        return ApiResult.ok(storeRoomList);
    }


    /**
     * 查看门店详情
     */
    @AppLog(value = "查看门店详情", type = 1)
    //@AuthCheck
    @GetMapping("/store/detail/{key}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "唯一的key", paramType = "query", dataType = "string")
    })
    @ApiOperation(value = "查看门店详情", notes = "查看门店详情")
    public ApiResult<StoreDto> detail(@PathVariable String key) {
        //Long uid = LocalUser.getUser().getUid();
        if (StrUtil.isEmpty(key)) {
            throw new XunyinException("参数错误");
        }
        StoreDto storeDto = storeService.queryStoreDtoById(Integer.parseInt(key));
        if (ObjectUtil.isNull(storeDto)) {
            throw new XunyinException("门店不存在");
        }
        return ApiResult.ok(storeDto);
    }

    /**
     * 查看门店的房间详情
     */
    @AppLog(value = "查看门店的房间详情", type = 1)
    //@AuthCheck
    @PostMapping("/storeoom/detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "唯一的key", paramType = "query", dataType = "string")
    })
    @ApiOperation(value = "查看门店的房间详情", notes = "查看门店的房间详情")
    public ApiResult<MtStoreRoomVo> storeRoomDetail(@RequestBody Map<String, Object> param) {
        //Long uid = LocalUser.getUser().getUid();
/*        if (StrUtil.isEmpty(key)) {
            throw new XunyinException("参数错误");
        }*/
/*        MtStoreRoom mtStoreRoom = mtStoreRoomMapper.selectById(Integer.parseInt(key));
        MtStoreRoomVo mtStoreRoomVo = new MtStoreRoomVo();
        BeanUtils.copyProperties(mtStoreRoom, mtStoreRoomVo);*/
        String latitude = param.get("latitude") == null ? "" : param.get("latitude").toString();
        String longitude = param.get("longitude") == null ? "" : param.get("longitude").toString();
        Integer storeRoomId = (param.get("storeRoomId") == null) ? 0 : Integer.parseInt(param.get("storeRoomId").toString());
        MtStoreRoomVo mtStoreRoomVo = mtStoreRoomMapper.getStoreRoomDetail(storeRoomId, latitude, longitude);
        log.info("mtStoreRoomVo.getStoreId():"+mtStoreRoomVo.getStoreId());
        log.info("mtStoreRoomVo.getStoreName():"+mtStoreRoomVo.getStoreName());
        if (ObjectUtil.isNull(mtStoreRoomVo)) {
            throw new XunyinException("房间不存在");
        }
        if (mtStoreRoomVo.getServerEndTime() != null) {
            String endTimeStr = DateUtil.parseDate2String(mtStoreRoomVo.getServerEndTime(), "yyyy-MM-dd HH:mm");
            endTimeStr = endTimeStr.substring(11);
            mtStoreRoomVo.setServerEndTimeStr(endTimeStr);
        }
        String serviceFacIdStr = mtStoreRoomVo.getServiceFacIds();
        if (serviceFacIdStr != null || !"".equals(serviceFacIdStr)) {
            String[] serviceFacIds = serviceFacIdStr.split(",");
            List<Map<String, String>> iconList = new ArrayList<Map<String, String>>();
            for (String serviceFacId : serviceFacIds) {
                Map<String, String> serviceFacMap = new HashMap<String, String>();
                serviceFacMap.put("id", serviceFacId);
                serviceFacMap.put("icon", redisUtils.getY("serviceFac_" + serviceFacId));
                iconList.add(serviceFacMap);
                //iconList.add(redisUtils.getY("serviceFac_"+serviceFacId));
            }
            mtStoreRoomVo.setIconList(iconList);
        }
        return ApiResult.ok(mtStoreRoomVo);
    }

    /**
     * 获取服务设施列表
     */
    @AppLog(value = "获取服务设施列表", type = 1)
    //@AuthCheck
    @PostMapping("/mtservicefac/getList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "唯一的key", paramType = "query", dataType = "string")
    })
    @ApiOperation(value = "获取服务设施列表", notes = "获取服务设施列表")
    public ApiResult<List<MtServiceFacVo>> getList(@RequestBody Map<String, Object> param) {
        //Map<String, Object> result = new HashMap<>();
        List<MtServiceFac> list = mtServiceFacService.list();
        List<MtServiceFacVo> listVo = new ArrayList<MtServiceFacVo>();
        for(MtServiceFac mtServiceFac :list){
            MtServiceFacVo mtServiceFacVo = new MtServiceFacVo();
            mtServiceFacVo.setServiceFacName(mtServiceFac.getServiceFacName());
            mtServiceFacVo.setId(mtServiceFac.getId());
            mtServiceFacVo.setServiceFacSort(mtServiceFac.getServiceFacSort());
            mtServiceFacVo.setChecked(false);
            listVo.add(mtServiceFacVo);
        }
        return ApiResult.ok(listVo);
    }

    /**
     * 新增、修改房间接口
     *
     * @return ApiResult<String>
     */
    @AppLog(value = "新增、修改房间接口", type = 1)
    //@AuthCheck
    @PostMapping("/storeoom/save")
    @ApiOperation(value = "新增、修改房间接口", notes = "新增、修改房间接口")
    public ApiResult<String> storeoomSave(HttpServletRequest request, @RequestBody MtStoreRoom resources) {
        Boolean flag = true;
        // 修改
        if(resources.getId()>0){
            flag = mtStoreRoomService.saveOrUpdate(resources);
        // 添加
        }else{
            flag = mtStoreRoomService.save(resources);
        }
        if(flag){
            return ApiResult.ok("提交成功");
        }else{
            return ApiResult.ok("提交失败");
        }
    }

    /**
     * 更新房间上线状态，A：有效/启用；D：无效 接口
     *
     * @return ApiResult<String>
     */
    @AppLog(value = "更新房间上线状态，A：有效/启用；D：无效 接口", type = 1)
    //@AuthCheck
    @PostMapping("/storeRoom/updateRoomOnlineStatus")
    @ApiOperation(value = "更新房间上线状态，A：有效/启用；D：无效 接口", notes = "更新房间上线状态，A：有效/启用；D：无效 接口")
    public ApiResult<String> updateRoomOnlineStatus(HttpServletRequest request, @RequestBody MtStoreRoom resources) {

        //String roomOnlineStatus = params.get("roomOnlineStatus") != null ? params.get("roomOnlineStatus").toString() : StatusEnum.ENABLED.getKey();
        //Integer roomId = params.get("roomId") == null ? 0 : Integer.parseInt(params.get("roomId").toString());

        mtStoreRoomService.updateRoomOnlineStatus(resources.getId(), resources.getRoomOnlineStatus());

        return ApiResult.ok("").setMsg("更新房间状态成功");
    }

    /**
     * 获取房间跟门店信息（房间单条信息）
     */
/*    @AppLog(value = "获取房间跟门店信息（房间单条信息）", type = 1)
    //@AuthCheck
    @PostMapping("/storeRoom/storeAndRoom")
    @ApiOperation(value = "获取房间跟门店信息（房间单条信息）", notes = "获取房间跟门店信息（房间单条信息）")
    public ApiResult<MtStoreAndRoomVo> getStoreAndRoom(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        Integer storeId = (param.get("storeId") == null) ? 0 : Integer.parseInt(param.get("storeId").toString());
        Integer storeRoomId = (param.get("storeRoomId") == null) ? 0 : Integer.parseInt(param.get("storeRoomId").toString());
        MtStoreAndRoomVo mtStoreAndRoomVo = mtStoreRoomMapper.getStoreAndRoom(storeId,storeRoomId);
        //log.info("storeRoomListV2 -> storeRoomListV2={}", storeRoomList.toString());
        //mtStoreVo.setStoreRoomList(storeRoomList);
        return ApiResult.ok(mtStoreAndRoomVo);

    }*/
}
